package qx.hyj.petrescue.Controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import qx.hyj.petrescue.VO.JsonResult;
import qx.hyj.petrescue.constens.ErrorCode;
import qx.hyj.petrescue.dto.LoginUser;
import qx.hyj.petrescue.entity.Family;
import qx.hyj.petrescue.entity.Users;
import qx.hyj.petrescue.entity.Volunteer;
import qx.hyj.petrescue.mapper.Usermapper;
import qx.hyj.petrescue.service.UserService;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@RestController
@RequestMapping("/Petrescue/users")
public class UserController {
     @Autowired
    private UserService userService;
     @Autowired
     private Usermapper usermapper;
    @Autowired
    private ServletContext servletContext;
    @PostMapping("/login")
    public JsonResult<JSONObject> login(@RequestBody LoginUser user, HttpServletResponse response){
        JSONObject loginResponse = new JSONObject();
        // 调用userService的login方法，获取token
        String t = Optional.ofNullable(userService.login(user)).orElse("");
        Users user1 = usermapper.login(user.getAccount());
        Cookie cookie = new Cookie("token",t);
        // 设置Cookie的路径为根路径
        cookie.setPath("/");
        // 设置Cookie的过期时间（单位为秒）
        cookie.setMaxAge(3600);
        loginResponse.put("user",user1);
        response.addCookie(cookie);
     return new  JsonResult<>(loginResponse);
    }

    @PostMapping("/adduser")
    public JsonResult<Users> addUser(@RequestBody Users user){
     Users user1 =  userService.addUser(user);
     if(user1 != null){return new JsonResult<>(user1);}else {
         return new JsonResult<>(null, ErrorCode.USER_ADD_FAIL);
     }
    }

    @PostMapping("/updateuser")
    public JsonResult<Users> updateUser(@RequestBody Users user, HttpServletRequest request){
     Integer userId = (Integer) request.getAttribute("id");
     Users user1 = new Users();
     user1.setId(userId);
      Integer ADDOK =  userService.updateUser(user,user1);
     if(ADDOK == 1){return new JsonResult<>(user);}else {
         return new JsonResult<>(null, ErrorCode.USER_UPDATE_FAIL);
     }
    }

    @PostMapping("/updateAvatar")
    public JsonResult<Users> updateAvatar(@RequestParam("picture") MultipartFile picture, HttpServletRequest request) {
        try {
            Integer userId = (Integer) request.getAttribute("id");
            // 生成唯一的文件名
            String originalFilename = picture.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uniqueFileName = UUID.randomUUID().toString() + extension;
            String uploadDir = servletContext.getRealPath("/static/images/head/");
            Path uploadPath = Paths.get(uploadDir);
            // 创建目录（如果不存在）
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 构建完整的文件路径
            Path filePath = uploadPath.resolve(uniqueFileName);
            // 保存文件
            picture.transferTo(filePath.toFile());
            Users user = new Users();
            Users u = new Users();
            u.setId(userId);
            user.setAvatar("/static/images/head/"+uniqueFileName);
            usermapper.updateUser(user,u);
return new JsonResult<>(user);
        } catch (IOException e) {
            e.printStackTrace();
            return new JsonResult<>(null, ErrorCode.USER_TX_FAIL);
        }
    }

    @PostMapping("/addFamily")
    public JsonResult<JSONObject> addFamily(Family family, HttpServletRequest request){
        JSONObject loginResponse = new JSONObject();
        Integer addFamily = usermapper.searchFamilyByPhone(family.getPhone());
        if(addFamily==null){
            Integer userId = (Integer) request.getAttribute("id");
            Users userCondition = new Users();
            userCondition.setId(userId);
                family.setUserid(userId);
                usermapper.addFamily(family);
                Users user = new Users();
                user.setJsfamily(1);
                usermapper.updateUser(user, userCondition);
                loginResponse.put("Jsfamily",1);
                return new JsonResult<>(loginResponse);
            }
        else {
           return new JsonResult<>(null, ErrorCode.FAMILY_ADD_FAIL);
        }
    }
    @PostMapping("/addVolunteer")
    public JsonResult<JSONObject> addVolunteer(Volunteer volunteer, HttpServletRequest request){
        JSONObject loginResponse = new JSONObject();
        Integer addVolunteer = usermapper.searchVolunteerByPhone(volunteer.getPhone());
        if(addVolunteer==null){
            Integer userId = (Integer) request.getAttribute("id");
            Users userCondition = new Users();
            userCondition.setId(userId);
            volunteer.setUserid(userId);
            usermapper.addVolunteer(volunteer);
            Users user = new Users();
            user.setZyz(1);
            usermapper.updateUser(user, userCondition);
            loginResponse.put("Zyz",1);
            return new JsonResult<>(loginResponse);
        }else {
            return new JsonResult<>(null, ErrorCode.VOLUNTEER_ADD_FAIL);
        }
    }

}
